<template>
  <div class="page-mobile_team">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="false"
      title="我的推广"
    ></white-header>
    <div class="team-header">
      <div class="header-title">
        <img src="/img/mobile/distribution_order.png" alt="" />
        <div>推广详情</div>
      </div>
      <div class="user-list">
        <div class="user-item one">
          <div class="user-top">{{totalList[0]}}</div>
          <div class="user-bottom">一级用户</div>
        </div>
        <div class="user-item two">
          <div class="user-top">{{totalList[1]}}</div>
          <div class="user-bottom">二级用户</div>
        </div>
        <div class="user-item three">
          <div class="user-top">{{totalList[2]}}</div>
          <div class="user-bottom">三级用户</div>
        </div>
      </div>
      <div class="count-price">
        累计推广金额（元）：<span class="price">{{distribution_info.profit ? distribution_info.profit.toFixed(2) : "0.00"}}</span>
      </div>
    </div>
    <div class="team-container">
      <div class="team-menu">
        <div :class="['menu-item',active == 'one'?'active':'']" @touchstart="handleChange('one')">一级用户</div>
        <div :class="['menu-item',active == 'two'?'active':'']" @touchstart="handleChange('two')">二级用户</div>
        <div :class="['menu-item',active == 'three'?'active':'']" @touchstart="handleChange('three')">三级用户</div>
      </div>
      <div class="user-box">
        <div class="box-item" v-for="(item, index) in team_list" :key="index">
          <div class="user-name">用户名：{{item.acName}}</div>
          <div class="user-time">绑定时间：{{trimDate(item.createTime)}}</div>
          <div :class="['tips',active == 'one'?'one':active == 'two'?'two':'three']">
            <span v-if="active == 'one'">一级用户</span>
            <span v-if="active == 'two'">二级用户</span>
            <span v-if="active == 'three'">三级用户</span>
          </div>
        </div>
        <div class="footer" v-show="team_list.length != 0">
          <span class="tips">我是有底线的</span>
        </div>
        <van-empty description="暂无用户" v-show="team_list.length == 0" />
      </div>
    </div>
  </div>
</template>

<script>
// import { getteam } from "~/api/index";
import { getMyTeam,getDistributionInfo } from "~/api/distribution";
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
export default {
  components: {
    WhiteHeader
  },
  scrollToTop: true,
  data() {
    return {
      page: 1,
      pageSize: 20,
      total: 0,
      records: 0,
      team_list: [],
      active: "one",
      totalList: [0, 0, 0],
      distribution_info:{},
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      }
    }),
    actived() {
      return this.$route.query.actived;
    }
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        var year = _date.getFullYear();
        var month = _date.getMonth() + 1;
        var date = _date.getDate();
        var hours = _date.getHours();
        var minutes = _date.getMinutes();
        if (month < 10) {
          month = "0" + month;
        }
        if (date < 10) {
          date = "0" + date;
        }
        if (hours < 10) {
          hours = "0" + hours;
        }
        if (minutes < 10) {
          minutes = "0" + minutes;
        }
        return year + "." + month + "." + date + " " + hours + ":" + minutes;
        // return `${_date.getFullYear()}.${_date.getMonth() +
        //   1}.${_date.getDate()} ${_date.getHours()}:${'0'+_date.getMinutes()}`;
      } else {
        return "未知";
      }
    },
    toPath(path) {
      this.$router.push(path);
    },
     async getDistributionInfo() {
        this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id,
      };
      let result = await getDistributionInfo(params);
      if (result && result.data && result.data.code == 200) {
        this.distribution_info = result.data.data;
        this.SET_IS_LOADING(false);
      } else {
        this.$toast("获取失败！");
        this.SET_IS_LOADING(false);
      }
    },
    handleChange(name) {
      this.$router.replace({
        path: "/m/my-team",
        query: {
          actived: name
        }
      });
      this.active = name;
      this.page = 1;
      this.getData();
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      // console.log(scrollTop+"+"+clientHeight+">="+scrollHeight);
      //适配处理:-120的是距离底部120px触发上拉加载，而不是触底加载
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (this.total <= this.team_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        this.getData("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 300);
    },
    async getData(fetch_type) {
      this.SET_IS_LOADING(true);
      let result = await getMyTeam({
        sort: "create_time",
        sortType: "desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize,
        userId: this.user_info.id,
        type:
          this.active && this.active == "one"
            ? 1
            : this.active && this.active == "two"
            ? 2
            : 3
      });
      if (result && result.data.code == 200) {
        if (fetch_type == "pullup") {
          this.team_list = [...this.team_list, ...result.data.data.rows];
        } else {
          this.team_list = result.data.data.rows;
        }
        // this.team_list.sort(function (a, b) {
        //   return b.createTime - a.createTime;
        // });
        this.total = result.data.data.total;
        this.records = result.data.data.records;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast("获取失败！");
      }
    },
    async getTotalList() {
      this.SET_IS_LOADING(true);
      let result1 = await getMyTeam({
        sort: "create_time",
        sortType: "desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize,
        userId: this.user_info.id,
        type: 1
      });
      let result2 = await getMyTeam({
        sort: "create_time",
        sortType: "desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize,
        userId: this.user_info.id,
        type: 2
      });
      let result3 = await getMyTeam({
        sort: "create_time",
        sortType: "desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize,
        userId: this.user_info.id,
        type: 3
      });
      if (
        result1 &&
        result1.data.code == 200 &&
        result2 &&
        result2.data.code == 200 &&
        result3 &&
        result3.data.code == 200
      ) {
        this.totalList = [
          result1.data.data.total,
          result2.data.data.total,
          result3.data.data.total
        ];
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast("获取失败！");
      }
    }
  },
  activated() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
    this.getData();
    this.getTotalList();
    this.getDistributionInfo();
  },
  deactivated() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  destroyed() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  created() {
    if (this.actived) {
      this.active = this.actived;
    } else {
      this.active = "one";
      this.handleChange("one");
    }
    console.log(this.$route);
    this.getData();
    this.getTotalList();
    this.getDistributionInfo();
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile_team {
  width: 7.2rem;
  min-height: 100vh;
  background-color: #f7f7fa;
  .footer {
      padding: 0.3rem;
      font-size: 0.26rem;
      color: #babec2;
      text-align: center;
      .tips {
        position: relative;
      }
      .tips::before {
        content: "";
        display: block;
        position: absolute;
        left: -1.7rem;
        top: 50%;
        transform: translateY(-1px);
        width: 1.5rem;
        height: 1px;
        background: #babec2;
      }
      .tips::after {
        content: "";
        display: block;
        position: absolute;
        right: -1.7rem;
        top: 50%;
        width: 1.5rem;
        transform: translateY(-1px);
        height: 1px;
        background: #babec2;
      }
    }
  .team-header {
    background-color: #ffffff;
    width: 7.2rem;
    height: 5.664rem;
    // border-top: 1px solid #ededf1;
    padding: .288rem .288rem 0rem;
    box-sizing: border-box;
    .header-title {
      display: flex;
      align-items: center;
      color: #313233;
      font-size: 0.3072rem;
      font-weight: bold;
      img {
        width: 0.384rem;
        height: 0.384rem;
        display: block;
        margin-right: 0.1rem;
        background-color: var(--theme-color);
      }
    }
    .user-list {
      margin-top: .8rem;
      margin-bottom: .8rem;
      width: 100%;
      display: flex;
      justify-content: space-between;
      .user-item {
        width: 33.3333%;
        height: 1.92rem;
        .user-top {
          width: 1.248rem;
          height: 1.248rem;
          border-radius: 50%;
          overflow: hidden;
          text-align: center;
          line-height: 1.248rem;
          color: #ffffff;
          font-size: 0.4992rem;
          margin: 0 auto;
        }
        .user-bottom {
          margin-top: 0.2rem;
          text-align: center;
          font-weight: bold;

          font-size: 0.2688rem;
        }
      }
      .user-item.one {
        .user-top {
          background-image: linear-gradient(
              -45deg,
              rgba(37, 115, 255, 0.44) 0%,
              rgba(91, 230, 229, 0.44) 100%
            ),
            linear-gradient(#5c98ff, #5c98ff);
          background-blend-mode: normal, normal;
          box-shadow: 0px 0px 12px 0px rgba(49, 129, 239, 0.44);
        }
        .user-bottom {
          color: #5b96ff;
        }
      }
      .user-item.two {
        .user-top {
          background-image: linear-gradient(
              -45deg,
              rgba(115, 198, 144, 0.44) 0%,
              rgba(187, 251, 209, 0.44) 100%
            ),
            linear-gradient(#84d29f, #84d29f);
          background-blend-mode: normal, normal;
          box-shadow: 0px 0px 12px 0px rgba(115, 198, 144, 0.44);
        }
        .user-bottom {
          color: #73c690;
        }
      }
      .user-item.three {
        .user-top {
          background-image: linear-gradient(
              -45deg,
              rgba(237, 133, 133, 0.44) 0%,
              rgba(255, 200, 200, 0.44) 100%
            ),
            linear-gradient(#ed8585, #ed8585);
          background-blend-mode: normal, normal;
          box-shadow: 0px 0px 12px 0px rgba(237, 133, 133, 0.44);
        }
        .user-bottom {
          color: #ed8585;
        }
      }
    }
    .count-price{
      border-top: 1px solid #ededf1;
      width: 100%;
      height: 1.3rem;
      line-height: 1.3rem;
      color: #313233;
      font-size: .2688rem;
      .price{
        font-size: .4608rem;
        color: #f99797;
      }
    }
  }
  .team-container{
    width: 7.2rem;
    margin-top: .2rem;
    background-color: #ffffff;
    .team-menu{
      width: 100%;
      height: .8rem;
      display: flex;
      justify-content: space-between;
      .menu-item{
        text-align: center;
        width: 33.333%;
        height: .8rem;
        line-height: .8rem;
        font-size: .288rem;
        font-weight: bold;
        color: #313233;
        position: relative;
        &.active{
          color: var(--theme-color);
        }
        &.active::after{
          content: "";
          display: block;
          width: 1rem;
          height: .04rem;
          background: var(--theme-color);
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          bottom: 0;
        }
      }
    }
    .user-box{
      width: 7.2rem;
      box-sizing: border-box;
      padding: .288rem 0;
      background-color: #ffffff;
      border-top: 1px solid #ededf1;
      .box-item{
        border-bottom: 1px solid #ededf1;
        padding: .2rem .288rem;
        position: relative;
        .tips{
          position: absolute;
          right: 0rem;
          top: .2rem;
          width: 1.632rem;
          height: .4608rem;
          line-height: .4608rem;
          text-align: center;
          font-weight: bold;
          font-size: .2496rem;
          border-radius: .2304rem 0 0 .2304rem;
          color: #ffffff;
        }
        .tips.one{
          background-color: #5b96ff;
        }
        .tips.two{
          background-color: #84d29f;
        }
        .tips.three{
          background-color: #fd9999;
        }
        .user-name{
          font-size: .3264rem;
          color: #4a4b4d;
          margin-bottom: .3rem;
        }
        .user-time{
          font-size: .2496rem;
          color: #adb0b3;
        }
      }
      .box-item:last-child{
        border: none;
      }
    }
  }
}
</style>
<style lang="scss">
.page-mobile_team {
}
</style>
